<template>
  <div class="basic-info">
    <el-form :model="form" ref="form" label-width="88px" size="mini" :rules="addRules" :disabled="formDisabled || mode === 'view'">
      <el-row :gutter="24">
        <el-col :xs="6" :sm="6" :md="8" :lg="8" :xl="8">
          <el-form-item label="编码：" prop="code">
            <el-input v-model="form.code" @blur="updateForm"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="6" :sm="6" :md="8" :lg="8" :xl="8">
          <el-form-item label="药品名称：" prop="drugName">
            <el-input v-model="form.drugName" @blur="updateForm"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="6" :sm="6" :md="8" :lg="8" :xl="8">
          <el-form-item label="拼音简码：" prop="pyCode" >
            <el-input v-model="form.pyCode" @blur="updateForm"></el-input>
          </el-form-item>
        </el-col>
        
        <el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8">
			<el-form-item label="药品别名：" prop="alis">
			  <el-input 
				v-model="form.alis" 
				@blur="updateForm"
				@input="handleAliasInput">
			  </el-input>
			</el-form-item>
		</el-col>
		  
		<el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8">
			<el-form-item label="别名简码：" prop="alisPyCode">
			  <el-input 
				v-model="form.alisPyCode" 
				@blur="updateForm"
				>
			  </el-input>
			</el-form-item>
		</el-col>
		
		<el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8">
			<el-form-item label="有效状态：" prop="state">
			  <el-select v-model="form.state" @change="updateForm">
					<el-option v-for="item in statusOptions" :key="item.id" :label="item.label" :value="item.id">
						<span>{{ item.label }}</span>
					</el-option>
			  </el-select>
			</el-form-item>
		</el-col>
		
        <el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8">
          <el-form-item label="药品规格：" prop="drugSpec">
            <el-input v-model="form.drugSpec" @blur="updateForm"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8">
          <el-form-item label="包装规格：" prop="pacSpec">
            <el-input v-model="form.pacSpec" @blur="updateForm"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8">
          <el-form-item label="剂量/单位：" prop="unitDose">
			  <div class="box" style="display: flex;justify-content: space-around;">
				<el-input v-model="form.unitDose"  prop="unitDose" @blur="updateForm"></el-input>
				<!-- 单位 -->
				<el-select v-model="form.dosUnt" filterable  prop="dosUnt" @change="updateForm" style="margin-left: 4px;">
				  <el-option v-for="item in getDosaUntOptions" :key="item.id" :label="item.label" :value="item.id">
				  	<span>{{ item.label }}</span>
				  </el-option>
				</el-select>
			  </div>
          </el-form-item>
        </el-col>
		
        <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="8">
          <el-form-item label="包装单位：" prop="pacUnt">
            <el-select 
              v-model="form.pacUnt" 
              filterable 
              @change="handlePacUntChange">
              <el-option 
                v-for="item in unitDoseOptions" 
                :key="item.id" 
                :label="item.label" 
                :value="item.id">
                <span>{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="包装数量：" prop="pacCnt">
            <el-input 
              v-model.number="form.pacCnt" 
              @blur="handlePacCntBlur"
              :disabled="formDisabled || mode === 'view' || (form.pacUnt && form.minUnt && form.pacUnt === form.minUnt)"
              min="1">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="5" :lg="5" :xl="8">
          <el-form-item label="最小单位：" prop="minUnt">
            <el-select 
              v-model="form.minUnt" 
              filterable 
              @change="handleMinUntChange">
              <el-option 
                v-for="item in unitDoseOptions" 
                :key="item.id" 
                :label="item.label" 
                :value="item.id">
                <span>{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8">
          <el-form-item label="最小剂量：" prop="minDose">
            <el-input v-model="form.minDose" prop="minDose" @blur="updateForm"></el-input>
			<el-select v-model="form.dosUnt" filterable prop="dosUnt" @change="updateForm" style="margin-left: 4px;">
				<el-option v-for="item in getDosaUntOptions" :key="item.id" :label="item.label" :value="item.id">
					<span>{{ item.label }}</span>
				</el-option>
			</el-select>
          </el-form-item>
        </el-col>
        
		<!-- 确保成本单价输入框也触发计算 -->
        <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="8">
          <el-form-item label="成本单价：" prop="costPric">
            <el-input 
              v-model="form.costPric"
              @input="handleCostPriceChange"
              @blur="handleCostPriceBlur"
              placeholder="请输入成本单价"
            ></el-input>
          </el-form-item>
        </el-col>
		
        <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="8">
          <el-form-item label="零售单价：" prop="salePric">
            <el-input v-model="form.salePric" disabled @blur="updateForm"></el-input>
          </el-form-item>
        </el-col>
        
        <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="8">
          <el-form-item label="零售单位：" prop="saleUnt">
            <el-select v-model="form.saleUnt" filterable @change="updateForm">
				<el-option v-for="item in saleWaysOptions" :key="item.id" :label="item.label" :value="item.id">
					<span>{{ item.label }}</span>
				</el-option>
<!--              <el-option label="最小单位" value="1"></el-option>
              <el-option label="包装单位" value="2"></el-option> -->
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="8">
          <el-form-item label="给药方式：" prop="medcWayId">
            <el-select v-model="form.medcWayId" filterable @change="updateForm">
              <el-option v-for="item in usedFrquIdOptions" :key="item.id" :label="item.label" :value="item.id">
              	<span>{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
		
		<el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="8">
		  <el-form-item label="加成方式：" prop="markUpId">
		    <el-select v-model="form.markUpId" @change="handleMarkUpChange">
				<el-option v-for="item in markUpOption" :key="item.id" :label="item.label" :value="item.id">
					<span>{{ item.label }}</span>
				</el-option>
		    </el-select>
		  </el-form-item>
		</el-col>
		<el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="8">
		  <el-form-item label="固定加成：" prop="markUpFixed">
		    <el-select v-model="form.markUpFixed" @change="updateForm">
		      <el-option v-for="item in YNoptions" :key="item.id" :label="item.label" :value="item.id">
		      	<span>{{ item.label }}</span>
		      </el-option>
		    </el-select>
		  </el-form-item>
		</el-col>
		<!-- 加成比例输入框 --> <!-- 新增专门处理手工比例加成的事件 -->
		<el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="8">
		  <el-form-item label="加成比例：" prop="markUpRate">
		    <el-input 
		      v-model="form.markUpRate" 
		      :disabled="form.markUpId !== 3"
		      @input="handleManualMarkUpRateChange" 
		      @blur="updateForm">
		      <template v-if="form.markUpId == 3" #append>%</template>
		    </el-input>
		  </el-form-item>
		</el-col>
		  <!-- 新增输入事件 -->
		<el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="8">
		  <el-form-item label="加成金额：" prop="markUpPric">
		    <el-input 
		      v-model="form.markUpPric" 
		      :disabled="form.markUpId !== 2"
		      @input="handleFixedMarkupChange"
		      @blur="updateForm">
		    </el-input>
		  </el-form-item>
		</el-col>
		
		
		
        <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="8">
          <el-form-item label="用药频率：" prop="usedFrquId">
            <el-select v-model="form.usedFrquId" filterable @change="updateForm">
              <el-option v-for="item in medcWayIdOptions" :key="item.id" :label="item.label" :value="item.id">
              	<span>{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="8">
          <el-form-item label="贵重类型：" prop="expensiveType">
            <el-select v-model="form.expensiveType" filterable @change="updateForm">
              <el-option v-for="item in expensiveTypeOptions" :key="item.id" :label="item.label" :value="item.id">
              	<span>{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="8">
          <el-form-item label="取整方式：" prop="roundUnt">
            <el-select v-model="form.roundUnt" filterable @change="updateForm">
              <el-option v-for="item in roundUntoptions" :key="item.id" :label="item.label" :value="item.id">
              	<span>{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="8">
          <el-form-item label="病案费别：" prop="mrsId">
            <el-select v-model="form.mrsId" filterable @change="updateForm">
              <el-option v-for="item in medicalRecordFeeOption" :key="item.id" :label="item.label" :value="item.id">
              	<span>{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        
       <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="8">
         <el-form-item label="毒麻类型：" prop="intxAnstType">
           <el-select v-model="form.intxAnstType" @change="updateForm">
             <el-option v-for="item in poisonousTypeOption" :key="item.id" :label="item.label" :value="item.id">
             	<span>{{ item.label }}</span>
             </el-option>
           </el-select>
         </el-form-item>
       </el-col>
       
       <!-- 药理类别部分 -->
         <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="8">
           <el-form-item label="药理类别：" prop="phamType1">
             <el-select 
               v-model="form.phamType1" 
               @change="handlePhamType1Change"
               placeholder="请选择">
               <el-option 
                 v-for="item in drugCategoryOption" 
                 :key="item.value" 
                 :label="item.label" 
                 :value="item.id">
               </el-option>
             </el-select>
           </el-form-item>
         </el-col>
         <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="8">
           <el-form-item label="药理类别II：" prop="phamType2">
             <el-select 
               v-model="form.phamType2" 
               @change="handlePhamType2Change" 
               :disabled="!form.phamType1"
               placeholder="请选择">
               <el-option 
                 v-for="item in drugCategoryChildOption" 
                 :key="item.value" 
                 :label="item.label" 
                 :value="item.id">
               </el-option>
             </el-select>
           </el-form-item>
         </el-col>
         <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="8">
           <el-form-item label="药理类别III：" prop="phamType3">
             <el-select 
               v-model="form.phamType3" 
               @change="updateForm"
               :disabled="!form.phamType2"
               placeholder="请选择">
               <el-option 
                 v-for="item in threeLevelDrugCategoryOption" 
                 :key="item.value" 
                 :label="item.label" 
                 :value="item.id">
               </el-option>
             </el-select>
           </el-form-item>
         </el-col>
		
      </el-row>
    </el-form>
  </div>
</template>

<script>
	// 在顶部引入pinyin-pro
	import { pinyin } from 'pinyin-pro';
	// axios
	import { getDrugUnt,selectDocVtByType,getMedicationFrequency,getDosaUnt,
		selectOneCateGory,selectTwoCateGory,selectThreeCateGory,getMedicationWay,getMedcas,
	} from "@/api/MedicenCata.js";
	// axios
	import { docMarkById } from "@/api/MedicenCata.js";
export default {
	inject: ['reload'], // 无痕刷新
  props: {
    form: {
      type: Object,
      required: true,
    },
	
    formDisabled: {
      type: Boolean,
      default: false
    },
    mode: {
      type: String,
      default: 'add' // 'add', 'edit', 'view'
    },
    disablePackingQuantity: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    isSameUnit() {
      // 检查包装单位和最小单位是否相同（比较id）
      return this.form.pacUnt && this.form.minUnt && 
             this.form.pacUnt === this.form.minUnt;
    }
  },
  data(){
  	return{
		unitDoseOptions:[], // 包装单位
		getDosaUntOptions:[], // 剂量单位
		getMinUntOptions:[], // 最小单位
		methodTypeOptions:[], // 默认制法
		// 新增选项数据
		unitChangeInProgress: false, // 防止单位变化时重复触发
		drugCategoryOption: [], // 药理类别选项
		drugCategoryChildOption: [], // 药理类别II选项
		threeLevelDrugCategoryOption: [], // 药理类别III选项
		usedFrquIdOptions:[], // 默认给药方式
		expensiveTypeOptions:[{id:1,label:'普价'},{id:2,label:'贵重'},{id:3,label:'昂贵'},{id:4,label:'免费'}], // 贵重类型
		roundUntoptions:[{id:1,label:'单次取整'},{ id:2,label:'总量取整'},{id:3,label:'处方取整'}], //取整方式
		poisonousTypeOption:[], // 毒麻
		YNoptions:[{id:0,label:'否',value:'否'},{id:1,label:'是',value:'是'}],
		statusOptions:[{id:0,label:'禁用'},{id:1,label:'可用'}],  
		saleWaysOptions:[{id:1,label:'最小单位'},{id:2,label:'包装单位'}],
		markUpOption:[ { id:1,label:'比例加成'},{ id:2,label:'固定加成'},{ id:3,label:'手工比例加成'},{ id:4,label:'不加成'}],
		medcWayIdOptions:[], // 用药频率
		medicalRecordFeeOption:[], //病案费别
		// 其他数据保持不变...
		addRules: {
			// 其他规则保持不变...
			markUpId: [{ required: true, message: " ", trigger: "blur" }],
			pacCnt: [
			    { required: true, message: '请输入包装数量', trigger: 'blur' },
			    { validator: this.validatePacCnt, trigger: 'blur' }
			],
			saleUnt: [{ required: true, message: " ", trigger: "change" }],
			pacUnt: [{ required: true, message: " ", trigger: "change" }],
			unitDose: [{ required: true, message: " ", trigger: "blur" }],
			minDose: [{ required: true, message: " ", trigger: "blur" }],
			dosUnt:[{ required: true, message: " ", trigger: "blur" }],
			roundUnt: [{ required: true, message: " ", trigger: "change" }],
			mrsId: [{ required: true, message: " ", trigger: "change" }],
			markUpRate: [ 
			  { 
				required: false, // 初始为非必填
				pattern: /^[1-9]\d*(\.\d+)?$/, 
				message: '请输入大于0的数字', 
				trigger: 'blur' 
			  }
			],
			minUnt: [{ required: true, message: " ", trigger: "change" }],
			// markUpPric: [ 
			//   { 
			// 	required: false,
			// 	pattern: /^[1-9]\d*(\.\d+)?$/, 
			// 	message: '请输入大于0的数字', 
			// 	trigger: 'blur' 
			//   }
			// ],
			costPric: [
			    { 
			      required: false, 
			      message: '成本单价不能为空', 
			      trigger: 'blur' 
			    },
			    { 
			      validator: (rule, value, callback) => {
			        if (value === '' || value === null || value === undefined) {
			          callback();
			          return;
			        }
			        
			        const numValue = parseFloat(value);
			        if (isNaN(numValue) || numValue < 0) {
			          callback(new Error('请输入大于等于0的数字'));
			        } else if (/\.\d{5,}/.test(value)) {
			          callback(new Error('最多允许四位小数'));
			        } else if (value.toString().length > 15) {
			          callback(new Error('长度不能超过15位'));
			        } else {
			          callback();
			        }
			      },
			      trigger: 'blur'
			    }
			  ],
			matchedMarkUpItems: [], // 存储匹配的加成率规则
		},
		computed: {
		  isSameUnit() {
		    // 检查包装单位和最小单位是否相同（比较id和label）
		    return this.form.pacUnt && this.form.minUnt && 
		           this.form.pacUnt === this.form.minUnt;
		  }
		},
	}
  },
  mounted() {
	  this.$nextTick(() => {
	    this.getDocVtByType(); // 确保毒麻类型选项最先加载
	    this.pacUnt(); // 包装单位
	    this.getDosaUnts(); // 最小单位
	    this.getMedicationFrequency(); // 给药方式
	    this.getDosaUnts(); // 剂量/单位
	    this.getMedicationWay(); // 用药频率 
	    this.getMedcas(); // 病案费别
	    this.selectOneCateGory(); //药理类别
		this.checkUnitSame(); // 初始检查单位是否相同
	  });
  	
  },
	methods: {
		updateForm() {
			this.$emit('update', this.form);
		},
	// // 包装单位聚焦
	// handlefoucsPac(){
	// 	this.pacUnt(); // 包装单位
	// },
	// // 毒麻聚焦
	// handlefoucsDm(){
	// 	this.getDocVtByType(); // 毒麻
	// },
	// // 给药方式
	// handlefoucsGy(){
	// 	this.getMedicationFrequency(); // 给药方式
	// },
	// // 剂量/单位
	// handlefoucsJl(){
	// 	this.getDosaUnts(); // 剂量/单位
	// },
	// handlefoucsYY(){
	// 	this.getMedicationWay(); // 用药频率 
	// },
	// handlefoucsBBFB(){
	// 	this.getMedcas(); // 病案费别
	// },
	resetForm() {
	  // 重置表单数据
	  this.form = {
	    ...this.form,
	    code: '',
	    drugName: '',
	    pyCode: '',
	    alis: '',
	    alisPyCode: '',
	    drugSpec: '',
	    pacSpec: '',
	    unitDose: '',
	    dosUnt: '',
	    pacUnt: '',
	    pacCnt: 1,
	    minUnt: '',
	    minDose: '',
	    costPric: '',
	    salePric: '',
	    saleUnt: '',
	    medcWayId: '',
	    markUpId: 1,
	    markUpFixed: 0,
	    markUpRate: '',
	    markUpPric: '',
	    usedFrquId: '',
	    expensiveType: 1,
	    roundUnt: '',
	    mrsId: '',
	    intxAnstType: '',
	    phamType1: '',
	    phamType2: '',
	    phamType3: '',
	    state: 1
	  };
	  
	  // 重置表单验证
	  if (this.$refs.form) {
	    this.$refs.form.clearValidate();
	  }
	},
	// 验证数字有效性
	  isValidNumber(value) {
	    return !isNaN(parseFloat(value)) && isFinite(value);
	  },
	 // 添加blur处理
	 handleCostPriceBlur() {
	   if (this.form.costPric && !isNaN(this.form.costPric) && parseFloat(this.form.costPric) > 0) {
	     // 确保失去焦点时格式化为4位小数
	     const numValue = parseFloat(this.form.costPric);
	     this.form.costPric = numValue.toFixed(4);
	     this.calculateSalePrice();
	   } else {
	     this.form.costPric = '';
	   }
	   this.updateForm();
	 },
	// 计算手工比例加成
	calculateManualMarkUp() {
	  if (this.form.markUpId !== 3 || !this.form.costPric || !this.form.markUpRate) {
	    return;
	  }
	  
	  const cost = parseFloat(this.form.costPric);
	  const rate = parseFloat(this.form.markUpRate) / 100;
	  
	  if (this.isValidNumber(cost) && this.isValidNumber(rate)) {
	    this.form.salePric = (cost * (1 + rate)).toFixed(4);
	    this.updateForm();
	  }
	},
	  
	// 处理固定加成金额变化
	handleFixedMarkupChange(value) {
	  if (this.form.markUpId === 2 && this.form.costPric) {
	    // 计算零售单价 = 成本单价 + 加成金额
	    const cost = parseFloat(this.form.costPric);
	    const markup = parseFloat(value) || 0;
	    
	    if (!isNaN(cost)) {
	      this.form.salePric = (cost + markup).toFixed(4);
	      this.updateForm();
	    }
	  }
	},
	// 包装数量失去焦点时处理
	handlePacCntBlur() {
	  if (this.form.pacUnt && this.form.minUnt && this.form.pacUnt === this.form.minUnt) {
	    this.form.pacCnt = 1;
	    this.$message.warning('包装单位和最小单位相同，包装数量必须为1');
	  }
	  this.updateForm();
	},
	// 包装单位选择变化
	  handlePacUntChange(value) {
	    if (this.unitChangeInProgress) return;
	    this.unitChangeInProgress = true;
	    
	    this.$nextTick(() => {
	      this.checkUnitSame();
	      this.unitChangeInProgress = false;
	      this.updateForm();
	    });
	  },
	  
	  // 最小单位选择变化
	  handleMinUntChange(value) {
	    if (this.unitChangeInProgress) return;
	    this.unitChangeInProgress = true;
	    
	    this.$nextTick(() => {
	      this.checkUnitSame();
	      this.unitChangeInProgress = false;
	      this.updateForm();
	    });
	  },
	  
	  // 检查单位是否相同
	    checkUnitSame() {
	      if (this.form.pacUnt && this.form.minUnt && this.form.pacUnt === this.form.minUnt) {
	        this.form.pacCnt = 1;
	        this.$message.info('包装单位和最小单位相同，包装数量已自动设置为1');
	      }
	    },
		
	  // 包装数量输入验证
	    validatePacCnt(rule, value, callback) {
	      if (this.isSameUnit && value !== 1) {
	        callback(new Error('当包装单位和最小单位相同时，包装数量必须为1'));
	      } else if (!/^[1-9]\d*$/.test(value)) {
	        callback(new Error('请输入大于0的正整数'));
	      } else {
	        callback();
	      }
	  },
	// 处理成本单价变化（也需要考虑固定加成情况）
	handleCostPriceChange(value) {
	  // 允许输入大于0的小数，包括0.001这样的小数值
	  if (value !== '' && !isNaN(value) && parseFloat(value) >= 0) {
	    // 保留用户输入的原样，不立即格式化
	    this.form.costPric = value;
	    
	    // 触发价格计算
	    this.calculateSalePrice();
	  } else {
	    this.form.costPric = '';
	  }
	},
		
	// 处理药品别名输入事件
	handleAliasInput(value) {
	  console.log('药品别名输入:', value);
	  // 自动生成别名简码
	  this.form.alisPyCode = this.getFirstLetter(value);
	  this.updateForm(); // 触发更新
	},
	// 新增方法：处理药理类别变化
	handlePhamType1Change(value) {
	  // 清空下级选择
	  this.form.phamType2 = '';
	  this.form.phamType3 = '';
	  
	  // 根据选择的值加载药理类别II选项
	  this.loadDrugCategoryChildOptions(value);
	  
	  this.updateForm();
	},
	
	// 专门处理手工比例加成(markUpId=3)的输入变化
	handleManualMarkUpRateChange(value) {
	  if (this.form.markUpId === 3 && this.form.costPric) {
	    // 手工比例加成需要将markUpRate除以100
	    const cost = parseFloat(this.form.costPric);
	    const rate = parseFloat(value) / 100;
	    
	    // 确保计算结果是数字且有效
	    if (!isNaN(cost) && !isNaN(rate)) {
	      this.form.salePric = (cost * (1+rate)).toFixed(2);
	      this.updateForm(); // 触发表单更新
	    }
	  }
	},
	// 新增方法：处理药理类别II变化
	handlePhamType2Change(value) {
	  // 清空下级选择
	  this.form.phamType3 = '';
	  
	  // 根据选择的值加载药理类别III选项
	  this.loadThreeLevelDrugCategoryOptions(value);
	  
	  this.updateForm();
	},
	
	// 加载药理类别II选项loadDrugCategoryChildOptions
	async loadDrugCategoryChildOptions(parentId) {
	    try {
	        // 获取选中的药理类别对象
	        const selectedCategory = this.drugCategoryOption.find(item => item.id === parentId);
	        
	        if (selectedCategory) {
	          // 使用选中的药理类别的idcode作为参数
	          const res = await selectTwoCateGory({idcode: selectedCategory.idcode});
	          if (res.code === 200) {
	            this.drugCategoryChildOption = res.data;
	          } else {
	            this.drugCategoryChildOption = [];
	          }
	        } else {
	          this.drugCategoryChildOption = [];
	        }
	    } catch (error) {
	        console.error('加载药理类别II选项失败:', error);
	        this.drugCategoryChildOption = [];
	  }
	},
	
	// 加载药理类别III选项
	async loadThreeLevelDrugCategoryOptions(parentId) {
	  try {
		// 获取选中的药理类别II对象
		const selectedCategory = this.drugCategoryChildOption.find(item => item.id === parentId);
		
		if (selectedCategory) {
		  // 使用选中的药理类别II的idcode作为参数
		  const res = await selectThreeCateGory({idcode: selectedCategory.idcode});
		  if (res.code === 200) {
			this.threeLevelDrugCategoryOption = res.data;
		  } else {
			this.threeLevelDrugCategoryOption = [];
		  }
		} else {
		  this.threeLevelDrugCategoryOption = [];
		}
	  } catch (error) {
		console.error('加载药理类别III选项失败:', error);
		this.threeLevelDrugCategoryOption = [];
	  }
	},
	// 处理别名简码输入事件
	handleAliasPyCodeInput(value) {
	  console.log('别名简码输入:', value);
	  this.updateForm(); // 触发更新
	},

	// 处理加成方式变化
	handleMarkUpChange(value) {
	// 根据不同的加成方式设置不同的逻辑
	  if (value === 1) { // 比例加成
		this.form.markUpPric = ''; // 清空加成金额
		this.form.markUpFixed = 0; // 设置为非固定加成
		if (this.form.costPric) {
		  this.calculateMarkUpRate(); // 调用API计算标准加成率
		} else {
		  this.$message.warning('请先输入成本单价');
		}
	  } 
	  else if (value === 2) { // 固定加成
	    this.form.markUpRate = ''; // 清空加成比例
	    this.form.markUpFixed = 1; // 设置为固定加成
	    if (this.form.costPric && this.form.markUpPric) {
	      // 如果已有成本单价和加成金额，立即计算
	      this.handleFixedMarkupChange(this.form.markUpPric);
	    }
	  }
	  else if (value === 3) { // 手工比例加成
	    this.form.markUpPric = ''; // 清空加成金额
	    this.form.markUpFixed = 0; // 设置为非固定加成
	    if (this.form.costPric && this.form.markUpRate) {
	      // 手工比例加成需要将markUpRate除以100
	      const rate = parseFloat(this.form.markUpRate) / 100;
	      this.form.salePric = (parseFloat(this.form.costPric) * rate).toFixed(2);
	    }
	  }
	  else if (value === 4) { // 不加成
	    this.form.markUpPric = 0; // 清空加成金额
	    this.form.markUpRate = ''; // 清空加成比例
	    this.form.markUpFixed = 0; // 设置为非固定加成
	    this.form.salePric = this.form.costPric; // 零售价=成本价
	  }
	  
	  this.updateForm();
	},
	  // 计算加成率和销售单价
	  // 计算加成率和销售单价
	  async calculateMarkUpRate() {
	    try {
	      // 确保是比例加成模式
	      if (this.form.markUpId !== 1) return false;
	      
	      // 确保成本单价存在
	      if (!this.form.costPric) {
	        this.$message.warning('请先输入成本单价');
	        return false;
	      }
	      
	      // 调用接口获取加成率规则
	      const res = await docMarkById({ 
	        costPric: this.form.costPric,
	        drugType: 1 // 只获取比例加成类型的规则
	      });
	      
	      if (res.code === 200) {
	        if (res.data && res.data.length > 0) {
	          // 过滤出匹配的区间
	          const matchedItems = res.data.filter(item => {
	            const min = Math.min(item.pricLmtLow, item.pricLmtTop);
	            const max = Math.max(item.pricLmtLow, item.pricLmtTop);
	            return this.form.costPric >= min && this.form.costPric <= max;
	          });
	          
	          if (matchedItems.length > 0) {
	            // 选择id最大的规则
	            const selectedRule = matchedItems.reduce((prev, current) => 
	              (prev.id > current.id) ? prev : current
	            );
	            
	            // 确保清空不相关字段
	            this.form.markUpPric = 0;
	            this.form.markUpFixed = 0;
	            
	            // 填充加成率
	            this.form.markUpRate = selectedRule.markUpRate;
	            
	            // 计算销售单价
	            this.calculateSalePrice();
	            
	            // 通知父组件表单已更新
	            this.updateForm();
	            
	            return true;
	          }
	        }
	        
	        // 如果没有匹配的加成率规则，显示提示
	        this.showMarkUpRatePrompt();
	        return false;
	      } else {
	        this.$message.error(res.message || '获取加成率失败');
	        return false;
	      }
	    } catch (error) {
	      console.error('计算加成率出错:', error);
	      this.$message.error('计算加成率出错');
	      return false;
	    }
	  },
	  // 显示加成率提示
	  showMarkUpRatePrompt() {
	    this.$confirm(
	      `当前未查询到西药价格 ${this.form.costPric} 相关的加成率，请前往药品加成率进行添加`, 
	      '提示', 
	      {
	        confirmButtonText: '去新增',
	        cancelButtonText: '关闭提示',
	        type: 'warning'
	      }
	    ).then(() => {
	      // 跳转到加成率设置页面
	      this.$router.push('/systemCatalogue/markUp');
	    }).catch(() => {
	      // 用户选择关闭提示
	      this.form.markUpRate = '';
	      this.form.salePric = '';
	      this.updateForm();
	    });
	  },
	// 计算销售单价
	calculateSalePrice() {
	  if (!this.form.costPric) return;
	  
	  const cost = parseFloat(this.form.costPric);
	  
	  if (this.form.markUpId === 1 && this.form.markUpRate) {
	    // 比例加成: 成本 * 加成率
	    const rate = this.form.markUpRate;
	    this.form.salePric = (cost * rate).toFixed(4);
	  } 
	  else if (this.form.markUpId === 2 && this.form.markUpPric) {
	    // 固定加成: 成本 + 固定金额
	    const markup = parseFloat(this.form.markUpPric);
	    this.form.salePric = (cost + markup).toFixed(4);
	  }
	  else if (this.form.markUpId === 3 && this.form.markUpRate) {
	    // 手工比例加成: 成本 * (1 + 手工比例/100)
	    const rate = parseFloat(this.form.markUpRate) / 100;
	    this.form.salePric = (cost * (1 + rate)).toFixed(4);
	  }
	  else if (this.form.markUpId === 4) {
	    // 不加成: 零售价=成本价
	    this.form.salePric = cost.toFixed(4);
	  }
	  
	  this.updateForm();
	},

	// 在成本单价blur事件中调用计算
	  handleCostPricBlur() {
		if (this.form.markUpId === 1 && this.form.costPric) {
		  this.calculateMarkUpRate();
		}
		this.updateForm();
	  },
	// 获取字符串的首字母
	getFirstLetter(str) {
	  if (!str || typeof str !== 'string') return '';
	  
	  try {
		// 使用正则提取所有汉字（过滤非汉字字符）
		const chineseChars = str.match(/[\u4e00-\u9fa5]/g) || [];
		if (chineseChars.length === 0) return '';

		// 对每个汉字获取拼音首字母
		const initials = chineseChars.map(char => {
		  const pinyinResult = pinyin(char, {
			toneType: 'none',
			type: 'array',
			multiple: false, // 只取第一个读音
		  })[0] || '';
		  return pinyinResult.charAt(0).toUpperCase();
		});

		// 组合成简码（如"中国" → "ZG"）
		return initials.join('');
	  } catch (error) {
		console.error('拼音转换失败:', error);
		return '';
	  }
	},
	// datas
	// 包装单位
	async pacUnt(){
		let res = await getDrugUnt();
		if(res.code===200){ this.unitDoseOptions=res.data.map(v => {return { label: v.name, ...v}}) }else{ this.$message.error(res.message) }
	},

	// 毒麻
	async getDocVtByType(){
	  let res = await selectDocVtByType();
	  this.poisonousTypeOption = res.data.map(v => {return { label: v.name, value: v.id, ...v}});
	  console.warn('毒麻类型选项不包含当前值:',  this.poisonousTypeOption);
	  // 确保当前表单中的毒麻类型值在选项中
	  // if(this.form.intxAnstType) {
	  //   const selectedOption = this.poisonousTypeOption.find(item => item.id === this.form.intxAnstType);
	  //   if(!selectedOption) {
	      // console.warn('毒麻类型选项不包含当前值:', this.form.intxAnstType);
	      // 如果当前值不在选项中，可以添加一个临时选项
	      // this.poisonousTypeOption.push({
	      //   id: this.form.intxAnstType,
	      //   label: `未知类型(${this.form.intxAnstType})`,
	      //   value: this.form.intxAnstType
	      // });
	    // }
	  // }
	},
	// 给药方式
	async getMedicationFrequency(){
		let res = await getMedicationFrequency();
		if(res.code===200){ this.usedFrquIdOptions=res.data.map(v => {return { label: v.name, ...v}}) }else{ this.$message.error(res.message) };
		console.log(this.usedFrquIdOptions,'this.usedFrquIdOptions');
	},
	// 用药频率
	async getMedicationWay(){
		let res = await getMedicationWay();
		if(res.code===200){ this.medcWayIdOptions=res.data.map(v => {return { label: v.name, ...v}}) }else{ this.$message.error(res.message) }
	},
	// 剂量单位
	async getDosaUnts(){
		let res = await getDosaUnt();
		if(res.code===200){ 
			// 最小单位 && 剂量单位
			this.getDosaUntOptions = this.getDosaUntOptions=res.data.map(v => {return { label: v.name, ...v}}) }else{ this.$message.error(res.message)
		}
	},
	//病案费别
	async getMedcas(){
		this.res = await getMedcas();
		if(this.res.code===200){ 
			this.medicalRecordFeeOption=this.res.data.map(v => {return { label: v.name, ...v}})
		}
	},
	// 药理类别
	async selectOneCateGory(){
		let res = await selectOneCateGory();
		if(res.code===200){ 
			this.drugCategoryOption=res.data
		}
	},
	
  }
}
</script>

<style lang="less" scoped>
/deep/ .el-form-item{
	margin-bottom: 8px;
}
.basic-info {
  padding: 4px;
  /deep/ .el-form-item__label{
	  font-size: 12px;
  }
  /deep/ .el-input__inner{
	  padding: 0 4px;
  }
  /deep/ .el-form-item__content{
	  display: flex;
	  justify-content: space-around;
  }
  /deep/ .el-input--mini .el-input__inner{
  	height: 26px;
  }
}
</style>